﻿using Autofac;
using BaiTu.DAL.EF.Provider;
using BaiTu.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaiTu.DAL.EF.Dependency
{
    public class DependencyRegister : IOCServices.IDependencyRegistrater
    {
        public void Register(ContainerBuilder builder, BaiTu.Framework.Core.TypeFinder.ITypeFinder typeFinder)
        {
            builder.Register(c => Config.DataSettingsConfig.GetConfig()).As<ConfigInfo.DataSettingsConfigInfo>();
            builder.Register(x => new EfDataProviderManager(x.Resolve<ConfigInfo.DataSettingsConfigInfo>())).As<BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IDataProvider>().InstancePerDependency();
            var dataProviderSettings = Config.DataSettingsConfig.GetConfig();
            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var efDataProviderManager = new EfDataProviderManager(Config.DataSettingsConfig.GetConfig());
                var dataProvider = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();
                builder.Register<IDBContext>(c => new BaiTuContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register<IDBContext>(c => new BaiTuContext(Config.DataSettingsConfig.GetConfig().DataConnectionString)).InstancePerLifetimeScope();
            }
            //builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IDAL.IRepository<>)).InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IDAL.IBaseRepository<>)).InstancePerLifetimeScope();
        }

        public int Order
        {
            get { return 200; }
        }
    }
}
